package com.chufan.bcproj;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.util.Set;

import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.User;
import org.hyperledger.fabric.sdk.identity.X509Enrollment;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;

public class LocalUser implements User { // 实现User接口
	private String name;
	private String mspId;
	private Enrollment enrollment;

	LocalUser(String name, String mspId,String keyFile, String certFile) {
		this.name = name;
		this.mspId = mspId;
		try {
			this.enrollment = loadFromPemFile(keyFile, certFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

//  private Enrollment loadFromPemFile(String keyFile,String certFile){ /*见下文说明*/ }
	private Enrollment loadFromPemFile(String keyFile, String certFile) throws Exception {
		byte[] keyPem = Files.readAllBytes(Paths.get(keyFile)); // 载入私钥PEM文本
		byte[] certPem = Files.readAllBytes(Paths.get(certFile)); // 载入证书PEM文本
		CryptoPrimitives suite = new CryptoPrimitives(); // 载入密码学套件
		PrivateKey privateKey = suite.bytesToPrivateKey(keyPem); // 将PEM文本转换为私钥对象
		return new X509Enrollment(privateKey, new String(certPem)); // 创建并返回X509Enrollment对象
	}

	public String getName() {
		return name;
	}

	public String getMspId() {
		return mspId;
	}

	public Enrollment getEnrollment() {
		return enrollment;
	}

	public String getAccount() {
		return null;
	}

	public String getAffiliation() {
		return null;
	}

	public Set<String> getRoles() {
		// TODO Auto-generated method stub
		return null;
	}
}
